<?php

namespace Home\Controller;

use Home\Org\Util\QQOpenConfig;
use \Home\Org\Util\QQOpenHelper;

require './vendor/autoload.php';

class ItDeptController{

    public function __construct()
    {
        import("@.ORG.Util.QQOpenConfig");
        import("@.ORG.Util.QQOpenHelper");

    }
    /**
     * @Description: 通过 QQ 返回的 code 获取 token
     */
    function getQQToken()
    {

        $code = I('code');
        if (isset($code)) {
            $query = array(
                'grant_type' => 'authorization_code',
                'app_id' => QQOpenConfig::APPID,
                'app_secret' => QQOpenConfig::APPSECRET,
                'code' => $code,
                'state' => md5(rand()),
                'redirect_uri' => QQOpenConfig::COMPANY_CALLBACK_URL,
            );

            $options = array(
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CONNECTTIMEOUT => 10,
                CURLOPT_TIMEOUT => 10,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_SSL_VERIFYPEER => false,
            );

            $url = QQOpenConfig::OAUTH2_TOKEN . '?' . http_build_query($query);
            $curl = curl_init($url);
            if (curl_setopt_array($curl, $options)) {
                $result = curl_exec($curl);
            }
            curl_close($curl);

            if (false !== $result) {
                $company_info = json_decode($result,true);
                //$company_id = $company_info['open_id'];
                //$access_token = $company_info['access_token'];
                //$time = time();
                //$expires_in = $company_info['expires_in'];
                //$refresh_token = $company_info['refresh_token'];
                $file = QQOpenConfig::FILE_NAME;
                file_put_contents($file,$result);
                //获取company_id和company_token目前只有这一个地方，所以建议用户将$company_id, $access_token, $time, $refresh_token, $expires_in存储下来

                if($company_info['access_token']) {
                    echo json_encode(array('ret' => 0)); //开放平台读到这个信息，就会开通成功
                }else{
                    echo json_encode(array('ret' => -1)); //读到这个信息，或者没有读到信息，会开通失败
                }

                die();
            }
        }

        die();

    }
    /**
     * @Description: 从 Dat 文件中获取 Token
     */
    function getQQTokenFromDat(){
        //echo "{\"ret\":1,\"msg\":\"code\u53c2\u6570\u975e\u6cd5\"}";
        $file = QQOpenConfig::FILE_NAME;
        $current = file_get_contents($file);
        $dataArray = json_decode($current,true);
        var_dump($dataArray);
        die();
    }
    /**
     * @Description: 跳转至 QQ，完成授权，获得 code
     */
    function getQQCode(){

        if (QQOpenConfig::APPID == '' || QQOpenConfig::APPSECRET == '' || QQOpenConfig::COMPANY_CALLBACK_URL == '' || QQOpenConfig::USER_CALLBACK_URL == '') {
            header("Content-type: text/html; charset=utf-8");
            echo '请先修改OpenConfig文件，填好APPID, APPSECRET, COMPANY_CALLBACK_URL, USER_CALLBACK_URL~有不理解之处请查看<a href="http://wiki.open.b.qq.com/api:start#api%E8%B0%83%E7%94%A8%E8%8C%83%E4%BE%8B%E4%BB%A3%E7%A0%81">开放平台示例使用说明.pptx</a>';
            //exit;
        }

        $url = QQOpenHelper::oauthCompany()->getAuthorizeUrl();

        header("Location:".$url);

    }

    function createEmailAccount(){

        /*
        $query = array(
            'userid' => 'apiTestingA.shi@g-town.com.cn',
            'name' => 'apiTestingA.shi',
            'department' => array(number_format(34353631791819764,0,'','')),
            'password' => 'ap1@Testing'
        );
        $jsonData = json_encode($query);
        */
        // 以上 json_encode 转换后的数据不能正常使用，department 值过大，需要手工拼接 json 数据

        $jsonData = "{\"userid\":\"apiTestingA.shi@g-town.com.cn\",\"name\":\"apiTestingA.shi\",\"department\":[34353631791819764],\"password\":\"ap1@Testing\"}";
        //echo $jsonData;die();

        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
        );

        $url = "https://api.exmail.qq.com/cgi-bin/user/create?access_token=Px5Mhix_II0GAaSrL1Fvh2hvqc7D0knJ9epUDAFYzr0QguLw4JQaiQBxcORvA-UdPV6nats6rNzXCnJTQEc1CQ";

        $data = $this->http($url,$jsonData,'POST');
        var_dump($data);

    }

    function http($url, $params, $method = 'GET', $header = array(), $multi = false) {
        $opts = array(CURLOPT_TIMEOUT => 30, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_HTTPHEADER => $header);

        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)) {
            case 'GET' :
                $opts[CURLOPT_URL] = $url . '?' . str_replace("&amp;", "&", http_build_query($params));
                break;
            case 'POST' :
                //判断是否传输文件
                //$params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default :
                throw new Exception('不支持的请求方式！');
        }

        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error)
            throw new Exception('请求发生错误：' . $error);
        return $data;
    }

    /**
     * @Decription: PHP 生成 PDF 使用类库 mpdf60.mpdf : Vendor('mpdf60.mpdf');
     */
    function generatePdf()
    {
        Vendor('mpdf60.mpdf');
        $mpdf=new \mPDF('zh-cn','A4', 0, '宋体', 0, 0);
        $html="<table align='center' width='90%' height='90%' border='1' cellpadding='0' cellspacing='0'>
<tr><td colspan='5' align='center'>创建帐号</td></tr>
<tr>
<td>姓名:</td>
<td>域帐号:</td>
<td>邮箱:</td>
<td>企业QQ:</td>
<td>密码:</td>
</tr>
<tr>
<td>时利刚</td>
<td>maxwell.shi</td>
<td>maxwell.shi@g-town.com.cn</td>
<td>2853045266</td>
<td>".$this->makePassword()."</td>
</tr>
<tr><td colspan='5' align='right'>海牙湾IT部</td></tr>
</table>";
        $mpdf->WriteHTML($html);
        $mpdf->Output();
        exit;
    }

    public function loginPowerShellServer()
    {
        //GT Server
        $ipadd = "192.168.1.22";
        $user = "G-town\\syser";
        $pass = "s@pz8k^i";

        $connection = ssh2_connect($ipadd,22);
        if (ssh2_auth_password($connection,$user,$pass))
        {
            echo "Authentication Successful! ";

            $stream = ssh2_exec($connection, 'mv 2.txt 3.txt');
            $dio_stream = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);  //获得标准输入输出留
            $err_stream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);  //获得错误输出留
            stream_set_blocking($err_stream, true);
            stream_set_blocking($dio_stream, true);
            $result_err = stream_get_contents($err_stream);
            $result_dio = stream_get_contents($dio_stream); //获取流的内容，即命令的返回内容
            var_dump($result_err);
            var_dump($result_dio);
            fclose($stream);

        }else{
            die("Authentication Failed...");
        }

    }


    public function makePassword(){

        $length = 8;

        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k','m', 'n', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D', 
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z','2', '3', '4', '5', '6', '7', '8', '9', '!',
'@','#', '$', '%', '&', '*', '(', ')', '-', '_',
'[', ']', '{', '}', '<', '>', '~',  '+', '=', ',', ';', ':', '?', '|');

        $keys = array_rand($chars,8);

        $password = '';
        for($i = 0; $i < $length; $i++)
        {
            $password .= $chars[$keys[$i]];
        }

        //echo $password;
        return $password;

    }

}